package org.jtsmix.editor;

import org.jtsmix.mixfile.*;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

public class MixReaderImpl implements MixReader {

    protected MixFile mixfile = null;

    @Override
    public void open(String fileName, GameType gameType) throws FileNotFoundException, IOException {
        if (mixfile != null && mixfile.isOpened()) {
            mixfile.close();
        }
        mixfile = new MixFileImpl();
        mixfile.open(fileName, gameType);
    }

    @Override
    public void extract(String fileToExtract, String outputFileName) {
        if (mixfile == null) {
            return;
        }

        if (!mixfile.contains(fileToExtract)) {
            return;
        }

        FileOutputStream fout = null;

        try {
            fout = new FileOutputStream(outputFileName);
        } catch (FileNotFoundException ex) {
            return;
        }

        try {
            mixfile.writeFileToStream(fileToExtract, fout);
            fout.close();
        } catch (IOException ex) {
            Logger.getLogger(MixReaderImpl.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    @Override
    public void extractAll(String outputDirectory) {
        File output = new File(outputDirectory);
        if (!output.isDirectory()) {
            throw new IllegalArgumentException("Cannot extract files. Output path is not a directory.");
        }

        for (String fileName : mixfile.getFileNameList()) {
            class R implements Runnable {

                private MixFile mixfile; // TODO remove mixfile?
                private String fileName;
                private String outputDirectory;

                public void setParams(MixFile mf, String fn, String od) {
                    mixfile = mf;
                    fileName = fn;
                    outputDirectory = od;
                }

                @Override
                public void run() {
                    extract(fileName, outputDirectory + File.separator + fileName);
                }
            }
            ;
            R r = new R();
            r.setParams(mixfile, fileName, outputDirectory);
            Thread t = new Thread(r);
            t.start();

        }
    }

    @Override
    public List<MixFileIndexEntry> getFileList() {
        return mixfile.getFileList();
    }

    @Override
    public boolean contains(String fileName) {
        return mixfile.contains(fileName);
    }

    @Override
    public List<String> getFileNameList() {
        return mixfile.getFileNameList();
    }

    @Override
    public MixInfo getMixInfo() {
        return mixfile.getMixInfo();
    }
}